import axios from "axios";
import {klBusinessStatistics} from "@/utils/urlConfig";
import {util} from "@/utils/util";
import {getUserInfo} from "@/model/appUser";

// 未登录情况进入 此时该js已经加载 变量已经是未登录情况下的赋值 所有请求头里字段需要登录后赋值的暂时没有 等下次重新进入加载赋值就有了
// const loginUser = getUserInfo()

// 允许跨域
axios.defaults.withCredentials = true

/*定义静态类对象*/
export class Http {
    /*不同的模块对应的基地址 项目中存在多个基地址 并且每个基地址对应了测试环境 预上线环境 生产环境*/
    static appModuleType = {
        moduleTypeOA:{
            baseUrlTest:'http://192.168.12.197:3001/business-xuanleoa-service/app/',
            baseUrlPro:'',
            baseUrlProduct:'http://yys.zhongwei-info.com/business-xuanleoa-service/app/'
        },
        moduleTypeVip:{
            baseUrlTest: 'http://192.168.12.197:3001/business-vip-service/app/',
            baseUrlPro:'',
            baseUrlProduct:'http://yys.zhongwei-info.com/business-vip-service-prod2/app/'
        },
        moduleTypeRecruit: {
            baseUrlTest: 'http://192.168.12.197:3001/business-recruit-service/app/',
            baseUrlPro:'',
            baseUrlProduct:'http://yys.zhongwei-info.com/business-vip-service-prod2/app/'
        },
        // none 说明给的是一个完整的链接
        none:1,
    };

    /*请求配置*/
    static reqConfig = {
        timeout: 6000,
        // 当前打包请求环境 0测试 1预上线 2生产环境
        appEnv: 2,
        // 请求异常时默认提示语
        errMsg:'您的网络连接异常，请检查网络连接',
        // 表单请求头设置
        formHeaders: this.getHeaders(false),
        // json请求头设置
        jsonHeaders: this.getHeaders(true),
        // 用以做请求方法版本切换 0 axios请求配置config部分直接使用静态变量 1直接在方法的config对象里配置 如果请求头内容动态变更 建议使用版本1
        version: 1,
    }

    /**
     * 创建axios对象 常规的表单提交
     * @type {axios.AxiosInstance}
     */
    static formHttp = axios.create({
        timeout: this.reqConfig.timeout,
        withCredentials: true,
        // 请求头设置
        // headers: this.getHeaders(false),
        // Cookie:"d2admin-2.0.5-lang=zh-chs; oms=0; celestia=QHIRCwSa2I7X8qNOsJwY3Eu8vt_mC0mCuhp2nbDhNhJY2vw7sJEcDg%3D%3D; celestia_uid=6471c85ae4b0799162c588da; ttms_username=18321567392; ttms_member_uid=5ec7441ce4b0bb8275298385; ttms_active=1; isMatched=1; level=2; celestia_level=101; ttms_logo=https%3A%2F%2Foss.56fanyun.com%2Fttms%2F44cdfea046f84053af7a6d80283b77cf.png; host_env=56fanyun; celestia_env=prod; host=wlhy.huayouwlkj.com"
    })

    /**
     * 创建axios对象 json提交
     * @type {axios.AxiosInstance}
     */
    static jsonHttp = axios.create({
        timeout: this.reqConfig.timeout,
        withCredentials: true,
        // 请求头设置
        headers: this.getHeaders(true)
    })


    /**
     * 创建axios对象 get方式
     * @type {axios.AxiosInstance}
     */
    static getHttp = axios.create({
        timeout: this.reqConfig.timeout,
        withCredentials: true,
        // 请求头设置
        headers: this.reqConfig.jsonHeaders
    })

    /**
     * 一般post请求 正常表单提交
     * @param url
     * @param moduleType
     * @param param
     * @returns {Promise<{msg: string, code: number, data: (*|null)}>}
     */
    static post(url, moduleType, param){
        const reqUrl = moduleType == 1 ? url : this.getTotalReqUrlBy(url, moduleType)
        if (this.reqConfig.version == 0) {
            return Http.formHttp.post(reqUrl, param).then(res => {
                return this.dealDataWithResult(res)
            }).catch(error => {
                if (error) {
                    const err = this.catchError(error)
                    throw err;
                }
            });
        } else {
            // 直接发起请求
           return axios.post(reqUrl, param, {
                withCredentials: true,
                // 请求头设置
                headers: {
                    Cookie:"d2admin-2.0.5-lang=zh-chs; oms=0; celestia_uid=6471c85ae4b0799162c588da; ttms_username=18321567392; ttms_member_uid=5ec7441ce4b0bb8275298385; ttms_active=1; isMatched=1; level=2; celestia_level=101; ttms_logo=https%3A%2F%2Foss.56fanyun.com%2Fttms%2F44cdfea046f84053af7a6d80283b77cf.png; host_env=56fanyun; celestia_env=prod; host=wlhy.huayouwlkj.com; acw_tc=2f624a4316854309435095022e021e24020df83b26e6ded2374e0aa9716281; celestia=aS40rhrdU_VXmV1jBvxaMvJr2xT84tyLDb-_Ns-_I0VY2vw7sJEcDg%3D%3D; ctms_node=s%3AktUWxsgfPJDACbI_-lniqHMfGk5x0D8X.x3gCJWXW1Ztc5IyZOYJc6bIo7YXJLsJ6YRoBcLbXduU; ttms_active=1"
                }
            }).then(res => {
                    return this.dealDataWithResult(res)
                }).catch(error => {
                    if (error) {
                        const err = this.catchError(error)
                        throw err;
                    }
                });
        }
    }

    /**
     * 请求参数以json形式提交
     * @param url
     * @param moduleType
     * @param param
     * @returns {Promise<{msg: string, code: number, data: (*|null)}>}
     */
    static jsonPost(url, moduleType, param) {
        const reqUrl = moduleType == 1 ? url : this.getTotalReqUrlBy(url, moduleType)
        return Http.jsonHttp.post(reqUrl, param).then(res => {
            window.console.log('post请求结果:', res);
            const data = this.dealDataWithResult(res)
            return data
        }).catch(error => {
            window.console.log('post请求出错:', error);
            if (error) {
                const err = this.catchError(error)
                throw err;
            }
        });
    }

    /**
     * get请求 参数在方法中以key=value&key=value连接 明文展示
     * @param url
     * @param moduleType
     * @param param
     * @returns {Promise<{msg: string, code: number, data: (*|null)}>}
     */
    static get(url, moduleType, param) {
        let reqUrl = moduleType == 1 ? url : this.getTotalReqUrlBy(url, moduleType)

        // get参数拼接在链接后面
        let paramStr = this.getParamStrBy(param)
        if (paramStr.length > 0) {
            reqUrl += '?' + paramStr
        }
        return Http.getHttp.get(reqUrl).then(res => {
            window.console.log('get请求结果:', res);
            const data = this.dealDataWithResult(res)
            return data
        }).catch(error => {
            window.console.log('get请求出错:', error);
            if (error) {
                const err = this.catchError(error)
                throw err;
            }
        });
    }

    /**
     * get提交时 参数格式转化
     * @param param
     * @returns {string|string}
     */
    static getParamStrBy(param) {
        let arr = []
        for (const paramKey in param) {
            // for..in遍历的是索引
            let str = paramKey + '=' + param[paramKey]
            arr.push(str)
        }
        let paramStr = arr.length > 0 ? arr.join('&') : ''
        return paramStr
    }

    /**
     * 请求成功数据处理 统一给到调用处格式
     * @param result
     * @returns {{msg: string, code: number, data: (*|null)}}
     */
    static dealDataWithResult(result) {
        console.log('message', result.headers.message)
        let code
        let msg
        if (result.headers.code > 0) {
            // 接口请求通了 但是状态标记在请求返回头里面
            code = result.headers.code
        } else {
            // 状态标记就在请求返回数据里
            code = result.data && result.data.code ? result.data.code : 0
        }

        if (result.headers.message && result.headers.message.length > 0) {
            // 接口请求通了 但是提示标记在请求返回头里面
            let base64Msg = result.headers.message
            // header中的msg为base64编码 base64转化为原本的编码
            msg = util.getDecodeBase64(base64Msg)
        } else {
            // 提示标记就在请求返回数据里
            msg = result.data && result.data.msg ? result.data.msg : ''
        }

        const data = {
            code,
            data: result.data ? result.data.data : null,
            msg
        }
        return data
    }

    /**
     * 请求失败错误处理
     * @param error 请求出错error
     * @returns {string}
     */
    static catchError (error) {
        if (typeof error === 'object') {
            error = this.reqConfig.errMsg;
        }
        error = typeof error == 'string' ? error : this.reqConfig.errMsg;
        return error;
    }

    /**
     * 根据请求板块获取该板块对应的基地址 区分不同环境
     * @param info
     * @returns {*}
     */
    static getBaseUrlByBaseInfo(info) {
        let baseUrl = ''
        if (this.reqConfig.appEnv == 0) {
            baseUrl = info.baseUrlTest
        } else if (this.reqConfig.appEnv == 1) {
            baseUrl = info.baseUrlPro
        } else {
            baseUrl = info.baseUrlProduct
        }
        return baseUrl
    }

    /**
     * 根据请求方法以及对应的板块地址信息获取本次请求的完整链接
     * @param url 请求方法部分
     * @param info 模块地址信息对象
     * @returns {string|*}
     */
    static getTotalReqUrlBy(url, info) {
        if (url.indexOf('http') != -1) {
            return url
        }
        let reqUrl = this.getBaseUrlByBaseInfo(info) + url
        return reqUrl
    }

    /**
     * 获取请求头
     * @returns {{te_method: string, te_version: string, xxl_sso_sessionid: string, oa_login_token: (*|string), method_type: string, mobileType: string, userId: (string|*), viewId: string, osVersion: string, loginName: string, osType: string, imei: string, dpi: string, "Content-Type": string}}
     */
    static getHeaders(isJson) {
        const loginUser = getUserInfo()
        const contentType = isJson ? 'application/json' : 'application/x-www-form-urlencoded'
        let headers = {
            'Content-Type': contentType,
            "imei": "529992A3-B3BD-4903-9B60-D56EF956C32E",
            "mobileType": "iPhone",
            "dpi": util.getDpi(),
            "te_method": "doAction",
            'te_version':'1',
            'method_type':'0',
            'viewId':'1',
            'osVersion':"1.7.9",
            'osType':'ios',
            'userId': loginUser && loginUser.userId ? loginUser.userId : "",
            'loginName':"102709013875",
            'xxl_sso_sessionid':'551228_83278051c2ab4fa0a240fa3004ae232e',
            'oa_login_token': loginUser && loginUser.oaLoginToken ? loginUser.oaLoginToken : "",
        }
        return headers
    }
}

/**
 * 测试axios最简单的post调用 返回一个promise
 */
const postWithUrl = (url, param, config) => {
    return axios.post(url, param, {
        withCredentials: true,
        // 请求头设置
        headers: {
            // 'Content-Type': 'application/x-www-form-urlencoded',
        }
    })
        .then(res => {
            return this.dealDataWithResult(res)
        }).catch(error => {
        if (error) {
            const err = this.catchError(error)
            throw err;
        }
    });
}

/**
 * 实例对象导出 通过对象调用其下所有属性方法 方法为对象的属性一样
 * @type {{postWithUrl: postWithUrl}}
 */
export const apiManager = {
    // 导出后 外部可以直接apiManager.postWithUrl使用
    postWithUrl,
}
